package com.etc.controller;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.etc.entity.User;
import com.etc.service.impl.UserServiceImpl;
import com.etc.util.PageData;
import com.google.gson.Gson;


/**
 * Servlet implementation class UserController
 */
@WebServlet("/UserController")
@MultipartConfig
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}
	UserServiceImpl service = new UserServiceImpl();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取参数 参数名op的值如果等于query才做查询
		String op = request.getParameter("op");
		//提升:加入session的判断:从session中获取用户登录的信息,如果有,才能执行查询,添加等等的操作
		HttpSession session = request.getSession();
		Object object = session.getAttribute("user");
		if (object != null) {
			adminOp(op,request,response,session);
		}else if ("login".equals(op)) {
			Login(request,response);
			
		}else if("checkName".equals(op)) {
			//普通用户验证用户名是否可用
			checkName(op,request,response);
			
		}
	}
	
	/**
	 * 验证用户名是否存在
	 * @param op
	 * @param request
	 * @param session
	 * @param response
	 * @author zww
	 * @throws IOException 
	 */
	private void checkName(String op, HttpServletRequest request,HttpServletResponse response) throws IOException {
		//设置字符格式编码
		response.setContentType("text/html;charset=utf-8");
		// 获取用户名
		String uname = request.getParameter("uname");
		//调用判断用户名的方法
		boolean flag = service.userNameCheck(uname);
		if (flag) {
			response.getWriter().print("可用");			
		}else {
			response.getWriter().print("用户名已存在");
		}
		
	}
    /**
     * 管理员登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
	private void Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//登录
		//得到用户输入的用户名和密码
		String userName=request.getParameter("uname");
		String userPwd=request.getParameter("upwd");
		//调用业务层登录方法
		User user = service.userLogin(userName, userPwd);
		if (user!=null) {
			//用户名和密码正确
			//只有管理员登录才能访问后台管理界面
			if (user.getU_status()==1 && user.getU_level()==2) {
				//判断用户是否记住密码
				String reme=request.getParameter("remember-me");
				if (reme!=null) {
					System.out.println("用户选择记住密码"+reme);
					//存
					Cookie cookie1=new Cookie("username", userName);
					Cookie cookie2 = new Cookie("userpwd", userPwd);
					Cookie cookie3 = new Cookie("checked", "checked");
					//设置cookie过期时间
					cookie1.setMaxAge(240);//单位:秒  4分钟
					cookie2.setMaxAge(240);
					cookie3.setMaxAge(240);

					response.addCookie(cookie1);
					response.addCookie(cookie2);
					response.addCookie(cookie3);
				}

				//提升->加入访问控制:登录成功后要将用户登录信息存储在session中
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				//跳转到后台管理界面
				request.getRequestDispatcher("back/show.jsp").forward(request, response);
			}
		}else {
			//用户名和密码错误,跳转登录界面:1.转发2.重定向
			response.sendRedirect("back/login.jsp");
		}

	}

	private void adminOp(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		if("userByPage_ajax".equals(op)) {
			userByPage_ajax(op, request, response,session);
		}else if("addUser".equals(op)) {
			addUser(op, request, response,session);
		}else if("deleteUser".equals(op)) {
			deleteUser(op, request, response,session);
		}else if("updateUser".equals(op)) {
			updateUser(op, request, response,session);
		}else if("queryUserByLike".equals(op)) {
			queryUserByLike(op, request, response,session);
		}

	}

	private void queryUserByLike(String op, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		// TODO Auto-generated method stub
		
	}

	private void updateUser(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		//接受参数
		String jsonString= request.getParameter("user");
		//获取java对象
		Gson gson =new Gson();
		User user = gson.fromJson(jsonString,User.class);
		//调用修改方法
		boolean flag = service.updateUser(user);
		//返回数据
		String jsonFlag=gson.toJson(flag);
		try {
			response.getWriter().print(jsonFlag);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void deleteUser(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		// TODO Auto-generated method stub
		
	}

	private void addUser(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		// TODO Auto-generated method stub
		
	}

	private void userByPage_ajax(String op, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		//设置查询默认值  用户未选择是默认第一页且查询所有
		int pageNo=1;
		int pageSize=10;
		String titleLike="";
		//如果用户选择了数据 则修改数据否则按照 默认数据处理
		if(request.getParameter("pageNo")!=null) {
			pageNo=Integer.parseInt(request.getParameter("pageNo"));
		}
		if(request.getParameter("pageSize")!=null) {
			pageSize=Integer.parseInt(request.getParameter("pageSize"));
		}
		if(request.getParameter("titleLike")!=null) {
			titleLike=request.getParameter("titleLike");
		}
		//调用业务层获取数据
		PageData pageData = service.getUserByLikeAndLimit(pageNo, pageSize, titleLike);
		//使用ajax返回请求页面
		Gson gson =new Gson();
		String json=gson.toJson(pageData);
		try {
			response.getWriter().print(json);
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
